using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using ProductManagement.Models;
using ProductManagement.Services;

namespace ProductManagement.ViewModels
{
    public class ProductListViewModel : BindableBase, INavigationAware
    {
        private readonly IProductService _productService;
        private readonly IRegionManager _regionManager;
        private readonly IDialogService _dialogService;
        
        private ObservableCollection<Product> _products = new();
        private ObservableCollection<Product> _filteredProducts = new();
        private ObservableCollection<string> _categories = new();
        
        private Product? _selectedProduct;
        private string? _selectedCategory;
        private string _searchText = "";
        private string _statusMessage = "准备就绪";

        public ProductListViewModel(IProductService productService, IRegionManager regionManager, IDialogService dialogService)
        {
            _productService = productService;
            _regionManager = regionManager;
            _dialogService = dialogService;

            // 初始化Commands
            RefreshCommand = new DelegateCommand(async () => await RefreshProductsAsync());
            AddProductCommand = new DelegateCommand(AddProduct);
            ViewProductCommand = new DelegateCommand<Product>(ViewProduct);
            EditProductCommand = new DelegateCommand<Product>(EditProduct);
            DeleteProductCommand = new DelegateCommand<Product>(async (product) => await DeleteProductAsync(product));
            FilterCommand = new DelegateCommand(ApplyFilter);
            ClearFilterCommand = new DelegateCommand(ClearFilter);
            SearchCommand = new DelegateCommand(Search);

            // 监听搜索文本变化
            PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(SearchText))
                {
                    if (string.IsNullOrWhiteSpace(SearchText))
                    {
                        ApplyFilter();
                    }
                }
            };
        }

        #region Properties

        public ObservableCollection<Product> Products
        {
            get { return _products; }
            set { SetProperty(ref _products, value); }
        }

        public ObservableCollection<Product> FilteredProducts
        {
            get { return _filteredProducts; }
            set { SetProperty(ref _filteredProducts, value); }
        }

        public ObservableCollection<string> Categories
        {
            get { return _categories; }
            set { SetProperty(ref _categories, value); }
        }

        public Product? SelectedProduct
        {
            get { return _selectedProduct; }
            set { SetProperty(ref _selectedProduct, value); }
        }

        public string? SelectedCategory
        {
            get { return _selectedCategory; }
            set { SetProperty(ref _selectedCategory, value); }
        }

        public string SearchText
        {
            get { return _searchText; }
            set { SetProperty(ref _searchText, value); }
        }

        public string StatusMessage
        {
            get { return _statusMessage; }
            set { SetProperty(ref _statusMessage, value); }
        }

        #endregion

        #region Commands

        public DelegateCommand RefreshCommand { get; }
        public DelegateCommand AddProductCommand { get; }
        public DelegateCommand<Product> ViewProductCommand { get; }
        public DelegateCommand<Product> EditProductCommand { get; }
        public DelegateCommand<Product> DeleteProductCommand { get; }
        public DelegateCommand FilterCommand { get; }
        public DelegateCommand ClearFilterCommand { get; }
        public DelegateCommand SearchCommand { get; }

        #endregion

        #region Command Methods

        private async Task RefreshProductsAsync()
        {
            try
            {
                StatusMessage = "正在加载产品...";
                
                // 加载产品
                var products = await _productService.GetAllProductsAsync();
                Products.Clear();
                foreach (var product in products)
                {
                    Products.Add(product);
                }

                // 加载分类
                var categories = await _productService.GetCategoriesAsync();
                Categories.Clear();
                Categories.Add("全部分类"); // 添加默认选项
                foreach (var category in categories)
                {
                    Categories.Add(category);
                }

                ApplyFilter();
                StatusMessage = $"已加载 {Products.Count} 个产品";
            }
            catch (Exception ex)
            {
                StatusMessage = $"加载产品失败: {ex.Message}";
            }
        }

        private void AddProduct()
        {
            _regionManager.RequestNavigate("ContentRegion", "AddProductView");
        }

        private void ViewProduct(Product product)
        {
            if (product != null)
            {
                var parameters = new NavigationParameters
                {
                    { "ProductId", product.Id },
                    { "Mode", "View" }
                };
                _regionManager.RequestNavigate("ContentRegion", "ProductDetailView", parameters);
            }
        }

        private void EditProduct(Product product)
        {
            if (product != null)
            {
                var parameters = new NavigationParameters
                {
                    { "ProductId", product.Id },
                    { "Mode", "Edit" }
                };
                _regionManager.RequestNavigate("ContentRegion", "AddProductView", parameters);
            }
        }

        private async Task DeleteProductAsync(Product product)
        {
            if (product == null) return;

            var parameters = new DialogParameters
            {
                { "title", "确认删除" },
                { "message", $"您确定要删除产品 '{product.Name}' 吗？" }
            };

            _dialogService.ShowDialog("ConfirmationDialog", parameters, async (result) =>
            {
                if (result.Result == ButtonResult.OK)
                {
                    try
                    {
                        StatusMessage = "正在删除产品...";
                        var success = await _productService.DeleteProductAsync(product.Id);
                        if (success)
                        {
                            Products.Remove(product);
                            ApplyFilter();
                            StatusMessage = "产品删除成功";
                        }
                        else
                        {
                            StatusMessage = "产品删除失败";
                        }
                    }
                    catch (Exception ex)
                    {
                        StatusMessage = $"删除产品失败: {ex.Message}";
                    }
                }
            });
        }

        private void ApplyFilter()
        {
            var filtered = Products.AsEnumerable();

            // 按分类筛选
            if (!string.IsNullOrEmpty(SelectedCategory) && SelectedCategory != "全部分类")
            {
                filtered = filtered.Where(p => p.Category.Equals(SelectedCategory, StringComparison.OrdinalIgnoreCase));
            }

            // 按搜索文本筛选
            if (!string.IsNullOrWhiteSpace(SearchText))
            {
                filtered = filtered.Where(p => 
                    p.Name.Contains(SearchText, StringComparison.OrdinalIgnoreCase) ||
                    p.Description.Contains(SearchText, StringComparison.OrdinalIgnoreCase) ||
                    p.Category.Contains(SearchText, StringComparison.OrdinalIgnoreCase));
            }

            FilteredProducts.Clear();
            foreach (var product in filtered)
            {
                FilteredProducts.Add(product);
            }

            StatusMessage = $"显示 {FilteredProducts.Count} / {Products.Count} 个产品";
        }

        private void ClearFilter()
        {
            SelectedCategory = "全部分类";
            SearchText = "";
            ApplyFilter();
        }

        private void Search()
        {
            ApplyFilter();
        }

        #endregion

        #region INavigationAware

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            // 检查是否有特定的筛选参数
            if (navigationContext.Parameters.ContainsKey("Category"))
            {
                var category = navigationContext.Parameters.GetValue<string>("Category");
                SelectedCategory = category;
            }

            // 当导航到此视图时，刷新数据
            RefreshCommand.Execute();
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // 离开视图时的清理工作
        }

        #endregion
    }
}